package net.courier.remoting.provider.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import net.courier.remoting.client.RequestSendClient;
import net.courier.remoting.protocol.RequestDatagram;
import net.courier.remoting.protocol.ResponseDatagram;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettySendClient implements RequestSendClient {
	private static final Logger LOGGER = LoggerFactory.getLogger(MethodInvokeHandler.class);

	private final Channel channel;
	private final EventLoopGroup group;

	private volatile boolean close = false;

	public NettySendClient(EventLoopGroup group, Channel channel) {
		this.group = group;
		this.channel = channel;
	}

	@Override
	public synchronized ResponseDatagram sendRequest(RequestDatagram datagram) {
		ResultReceiveHandler handler = new ResultReceiveHandler(new ClientPromise(channel));
		registHandler(channel, handler);
		try {
			channel.write(new RequestDatagram());
			ResponseDatagram result = handler.getClientPromise().get();
			return result;
		} catch (Exception e) {
			close();
			return null;
		}

	}

	public void close() {
		try {
			if (close) {
				return;
			}

			close = true;
			if (channel == null) {
				return;
			}
			
			channel.close().sync();
		} catch (Exception e) {
			LOGGER.warn("关闭客户端失败", e);
		} finally {
			this.group.shutdownGracefully();
		}

	}

	@Override
	public boolean isActive() {
		return (!close && channel != null);
	}
	
	private void registHandler(Channel channel, ResultReceiveHandler handler) {
		String handlerName = "ResultReceiveHandler";
		ChannelPipeline pipeline = channel.pipeline();
		if(pipeline.context(handlerName) != null) {
			pipeline.remove(handlerName);
		}
		pipeline.addLast(handlerName, handler);
		
	}
}
